Ext.require([
    'Ext.form.field.ComboBox',
    'Ext.form.FieldSet',
    'Ext.tip.QuickTipManager',
    'Ext.data.*'
]);

Ext.require([
             'Ext.tree.*',
             'Ext.window.MessageBox',
             'Ext.data.*'
            ]);
Ext.require(['Ext.tab.*']);
Ext.require(['*']);




//~~~~~~~~~~~~~~~~~~~~~grid~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

Ext.Loader.setConfig({
  enabled: true
});

Ext.Loader.setPath('Ext.ux', '../extjs/examples/ux');

Ext.require([
           'Ext.grid.*',
           'Ext.data.*',
           'Ext.ux.RowExpander',
           'Ext.selection.CheckboxModel'
       ]);

Ext.require([
             'Ext.selection.CellModel',
             'Ext.util.*',
             'Ext.state.*',
             'Ext.form.*',
             'Ext.ux.CheckColumn'
         ]);

 


//~~~~~~~~~~~~~~~~~~~~~~~~数据库下拉菜单~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

var databaseGroupCombo ;
var tableInfo;
var tableGroupCombo ;
var tableStore;

Ext.onReady(function() {
	
  Ext.define("DatabaseGroup", {
      extend: "Ext.data.Model",
      fields: [
          { name: "id" },
          { name: "name" }
      ]
  });

  var store = Ext.create("Ext.data.Store", {
      model: "DatabaseGroup",
      proxy: {
          type: "ajax",
          url: "wiki/getDatabaseInfo.json",
          reader: new Ext.data.JsonReader({ model: "DatabaseGroup" })
      }
  });

  databaseGroupCombo = Ext.create('Ext.form.field.ComboBox', {
	    fieldLabel: '数据库',
	    renderTo: Ext.getBody(),
	    displayField: 'name',
	    width: 250,
	    labelWidth: 40,
	    store: store,
	    typeAhead: false,
	    editable:false,
	    padding:'0 0 0 5',
        name: 'DatabaseGroup',
        triggerAction: 'all',
        displayField: 'name',
        valueField: 'id',
        queryMode: 'remote',
        emptyText:'请选择' 
	});
  
  databaseGroupCombo.on('change', function(field, newValue, oldValue, obj) {
	  
		  	   if (newValue == "" || newValue == undefined) {
		  		    return;
		  	   }
		  	   
		  	   tableInfo = [];
	   	       tableGroupCombo.store.loadData(tableInfo);
	   	       tableGroupCombo.setVisible(false);
	   	        
		       Ext.Ajax.request({
			   	    url: 'wiki/getTableInfo.json',
			   	    params: {
			   	    	dbId : newValue
			   	    },
			   	    success: function(response){
			   	        var text = response.responseText;
			   	        var datas = Ext.decode(response.responseText);
			   	        tableInfo = datas;
			   	        tableGroupCombo.store.loadData(tableInfo);
			   	        tableGroupCombo.setVisible(true);
			   	    }
		       });
		       
		});   
  
});


//~~~~~~~~~~~~~~~~~~~~~~~~数据表下拉菜单~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Ext.onReady(function() {
	
tableInfo = [];
	
tableStore = Ext.create("Ext.data.ArrayStore", {
    autoDestroy: true,
    idIndex: 0,
    fields:[
            'name',
            {name:'id',type:'string'}
           ],
    data: tableInfo
});



tableGroupCombo = Ext.create('Ext.form.field.ComboBox', {
	    fieldLabel: '数据表',
	    renderTo: Ext.getBody(),
	    displayField: 'name',
	    width: 300,
	    labelWidth: 40,
	    store: tableStore,
	    typeAhead: false,
	    editable:true,
	    padding:'0 0 0 5',
        name: 'TableGroup',
        triggerAction: 'all',
        displayField: 'name',
        valueField: 'id',
        queryMode: 'local',
        emptyText:'输入可补全。选中则立即查询该表',
        hidden:true
	});
});


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

//function getSelectedText(tf){ 
//    var selectedText; 
////    var textField=tf.getEl().dom;
////    var textField=document.getElementById('sqlTextarea'); 
//    var textField=document.getElementById('sqlTextarea');
//	alert(textField);
//    if(window.getSelection) selectedText=getTextFieldSelection(tf);//getTextFieldSelection(document.getElementById("inputTextArea")); 
//    else selectedText=document.selection.createRange().text; 
//        alert(selectedText); 
//} 
//
//function getTextFieldSelection(tf){ 
//	tf.setReadOnly(false);
//	tf.show();//用其他函数可能也行，反正就是更新一下
//	var e = tf.getEl().dom;
//	var textField=document.getElementById('sqlTextarea');
//	alert(textField);
//	alert(textField.value);
//    //var oEvent=arguments.callee.caller.arguments[0]; 
//    if(e.selectionStart != undefined && e.selectionEnd != undefined) 
//        return e.value.substring(e.selectionStart,e.selectionEnd); 
//    else return ""; 
//} 

function getRangeByElement(obj) {
	var word = '';
	if (document.selection) {
		// IE
		obj.focus();
		selectobj = document.selection.createRange();
		if (selectobj.text.length > 0) {
			word = selectobj.text;
			document.selection.empty();
		}
	} else {
		p1 = obj.selectionStart;
		p2 = obj.selectionEnd;
		if (p1 || p1 == '0') {
			if (p1 != p2){
				word = obj.value.substring(p1, p2);
				obj.selectionStart=0;
				obj.selectionEnd=0;
			}
		}
	}
	return word;
}

//
//
////获取文本框选中的文本
//function getSelectedText(_processText){
////	var res="选中失败？?!!";
////	if(document.selection){//IE
////	res=document.selection.createRange().text;
////	}
////	else{//non-IE
////	_processText.setReadOnly(false);//readonly==true时chrome无法获取start和end，但我的代码需要用到readonly，这里只好临时赋false
////	_processText.show();//用其他函数可能也行，反正就是更新一下
////	var d=_processText.el.dom;
////	var start=d.selectionStart;
////	var end=d.selectionEnd;
////	var text=_processText.getRawValue();
////	res=text.substring(start,end);
////	_processText.setReadOnly(true);
////	}
////	return res;
//	var res="选中失败？?!!";
//	if(document.selection){
//		alert(document.selection.createRange().text);
//	} else {
//		_processText.setReadOnly(false);//readonly==true时chrome无法获取start和end，但我的代码需要用到readonly，这里只好临时赋false
//		alert(1);
//		_processText.show();//用其他函数可能也行，反正就是更新一下
//		alert(2);
//		var d=_processText.el.dom;
//		alert(3);
//		alert(d);
//		var start=d.selectionStart;
//		alert(4);
//		var end=d.selectionEnd;
//		alert(5);
//		var text=_processText.getRawValue();
//		alert(6);
//		alert(text);
//		res=text.substring(start,end);
//		alert("start=" + start + ",end=" + end)
//		alert(7);
//		_processText.setReadOnly(true);
//		alert(8);
//	}
//	alert(res);
//}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~viewport~~~~~~~~~~~~~~~~~~~~~~~~~~~~

//wiki表格
var progrid;
//数据源
var sds;
//列模式
var columns;

/**
 * 获取选中的行的数据的WIKI文本
 * @returns
 */
function getSelectedRowWiki()  
{  
    var record = progrid.getSelectionModel().getSelection();
    
    if(record == null || record.length == 0)
       return "";  
    
    var dataWiki = "";
    for(var i = 0; i < record.length; i++){
    	var rowWiki = "|";
    	for (var j = 1; j < columns.length; j++) {
    		  var fieldName = columns[j].header;
    		  var fieldValue = record[i].get(fieldName);
    		  rowWiki = rowWiki + fieldValue + "|";
    	}
    	dataWiki = dataWiki + rowWiki + "\r\n";
    }
    return dataWiki;  
}  


//function copierInit() {
//	ZeroClipboard.setMoviePath( f_getRootPath() + "/javascript/common/ZeroClipboard.swf" );  
//	alert(f_getRootPath());
//	clip = new ZeroClipboard.Client();
//	alert(5);
//	clip.setHandCursor( true );
////	clip.addEventListener('load', my_load);
////	clip.addEventListener('mouseOver', my_mouse_over);
////	clip.addEventListener('complete', my_complete);
//	clip.glue( 'rMenu5' );
//	alert(4);
////	clip.setText('123488888');
//}



Ext.onReady(function() {
	
	var sqlTextareaPanel = new Ext.form.Panel({
        frame: false,
        bodyPadding: 0,
        layout:'fit',
        collapsible: true,
        header:false,
        renderTo: Ext.getBody(),
        border :false,
        title: 'SQL输入框',
        items: [{
//            xtype: "textarea",
              html: '<textarea id=\"sqlTextarea\"  style=\"border:0;width:100%;height:100% !important;height:100;resize:none;\" ></textarea>',
//            id: "sqlTextarea",
//            anchor    : '100%',
              layout:'fit'
//            border: false,
//              emptyText : '请输入SQL，仅支持Select语句'
        }] 
    });
	
           var  vp =  Ext.create('Ext.Viewport', {
                 layout: {
                     type: 'border',
                     padding: 5
                 },
                 defaults: {
                     split: true
                 },
                 items: [{
                     region: 'north',
                     collapsible: false,
                     title: '',
                     split: true,
                     height: 35,
                     minHeight: 35,
                     bodyStyle:'background-color:#DDE7F4',
                     border:false,
                     html: '<span style=\"font-weight:bold;font-size:25px; color:#03336F;\">Easy Wiki</span> | <span style=\"font-size:13px; color:#03336F;\">良无限测试Wiki文件生成工具</span>'
                 },{
                     region: 'center',
                     layout: 'border',
                     border: true,
                     resizable:false,
                     title: '操作台',
                   	 dockedItems: [{
                         xtype: 'toolbar',
                         dock: 'top',
                         minHeight: 30,
                         items: [
							{
							    text: '运行SQL',
							    iconCls:'execute2-button',
							    handler: function(){
							    	
							    	
							    	var databaseId = databaseGroupCombo.getValue();
							    	if (databaseId == null) {
							    		 Ext.MessageBox.alert('提示信息', '请先选择你要使用的数据库。');
							    		 return;
							    	 }
							    	
							    	
//							    	alert(document.getElementById("sqlTextarea").value);
//							    	var sql = sqlTextareaPanel.getForm().findField("sqlTextarea").getValue();
							    	
							    	var sql = getRangeByElement(document.getElementById("sqlTextarea"));
							    	
							    	if (sql == "") {
							    		sql = document.getElementById("sqlTextarea").value;
							    	}
							    	
							    	if (sql == "") {
							    		 Ext.MessageBox.alert('提示信息', '请输入SQL语句。');
							    		 return;
							    	}
							    	
							    	//getSelectedText(sqlTextareaPanel.getForm().findField("sqlTextarea"));
							    	
							    	//return;
							    	
							        if (progrid != null) {
							        	progrid.reconfigure([], columns);
							        }
							        
							        var myMask = new Ext.LoadMask(Ext.getBody(), {//也可以是Ext.getCmp('').getEl()窗口名称
							        	msg    : "查询中，请稍候...",//你要写成Loading...也可以
							        	msgCls : 'z-index:10000;',
							        	removeMask : true// 完成后移除
							        });
							        myMask.show();
							        
							    	var conn = new Ext.data.Connection();
							    	conn.request({
								    	url:'wiki/executeSql.json?dbInfoId=' + databaseId + "&sql=" + sql,
								    	
								    	callback:function(options, success, response){
									    	var json = Ext.decode(response.responseText);
									    	
									    	if (json.errorFlag) {
									    		myMask.hide();
									    		Ext.MessageBox.alert('出错啦！', json.message);
									        	return;
									    	}
									    	
									    	columns = json.columModle;
//									    	var scm = new Ext.grid.ColumnModel(json.columModle);
									    	
									        sds = new Ext.data.JsonStore({
										    	data: json.data,
										    	fields:json.fieldsNames
									    	});
									    	
									        cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
									    	    dbclicksToEdit: 1
									    	});
									        
									        if (progrid != null) {
									        	progrid.reconfigure(sds, columns);
									        	myMask.hide();
									        	return;
									        }
									        
									        //右键菜单
									        //创建右键菜单选项键
									        var rightMenu = new Ext.menu.Menu({
									                 id:'rightclickCount',
									                 items:[
														        {
															        id:'rMenu1',
															        text:'复制Wiki文本',
															        handler:function(){
															        	
															        	//表头的WIKI文本
															        	var headerWiki = "|";
															        	for (var i = 1; i < columns.length; i++) {
															        		headerWiki = headerWiki + columns[i].header + "|";
															        	}
															        	
															        	var rowWiki = getSelectedRowWiki();
															        	var allWiki = headerWiki + "\r\n" + rowWiki;
															        	
															        	if (Ext.isIE){
															        		window.clipboardData.setData("Text", allWiki);
															        	} else {
															        		 
//																		        var copyMask = new Ext.LoadMask(Ext.getBody(), {//也可以是Ext.getCmp('').getEl()窗口名称
//																		        	title:'8888',
//																		        	defaultType: 'textarea',
//																		        	msg:'<textarea>' + allWiki + '</textarea>',
//																		        	msgCls : 'z-index:10000;',
//																		        	removeMask : true// 完成后移除
//																		        });
//																		        copyMask.show();
																		        
															        		
																		        $("#copyTextarea").text(allWiki);
//																        		
//															        		    $.blockUI({ 
//															        		    	message: $("#copyDiv"),
//															        		    	title:'手工复制窗口',
//															        		    	css: { 
//															        		    		cursor:    'pointer',
//															        		            top:  ($(window).height() - 400) /2 + 'px', 
//															        		            left: ($(window).width() - 400) /2 + 'px', 
//															        		            width: '500px' 
//															        		        }
//															        		    });
//															        		    
//																        		ZeroClipboard.setMoviePath( f_getRootPath() + "/javascript/common/ZeroClipboard.swf" );  
//																        		var clip = new ZeroClipboard.Client();
//																        		clip.setHandCursor( true );
//																        		clip.setText("1234");
//																        		clip.glue( 'd_clip_button' );
																		        
//																		  	  var copyWin =  Ext.MessageBox.show({
//																		          title: '当前浏览器不支持自动复制',
//																		          msg: '请鼠标移进文本域，CTRL+C手动复制:<br/><br/><textarea  cols="60" rows="5" onmousemove="this.select();" id="copyTextarea" style="width:300px; word-wrap : normal; resize:none; ">' + allWiki + '</textarea>',
//																		          width:320,
//																		          buttons: Ext.MessageBox.OK,
//																		          buttonText:{
//																		               ok: "关闭" 
//																		          }
////																		          fn: showResultText,
////																		          animateTarget: 'mb3'
//																		      });
															        		    
															        		     
															        		 
															        	}
															        	
															        }
														        },{
														        	id:'rMenu2',
															        text:'删除选中行',
															        handler:function(){}
														        },{
														        	id:'rMenu3',
															        text:'仅保留选中行',
															        handler:function(){}
														        },{
														        	id:'rMenu4',
															        text:'复制并插入',
															        handler:function(){}
														        },{
														        	id:'rMenu5',
															        text:'自动生成数据',
															        handler:function(){}
														        }
													        ]
									         
									        });
									        
									        
									        var wikiGridHeight = Ext.get('wikiGridId').getHeight();
									        progrid = new Ext.grid.GridPanel({
//										    	el : 'left',
//										    	ds : sds,
//										    	cm : scm,
										    	store:sds,
										    	columns:columns,
										    	columnLines: true,
										    	stateful: true,
										        collapsible: false,
										        multiSelect: true,
//										        stateId: 'stateGrid',
										        title: '',
										    	loadMask : true,
										    	renderTo: 'wikiGrid',
//										    	renderTo: Ext.getBody(),
										    	header:false,
										    	multiSelect: true,
										    	autoScroll:true,
//										        layout:'column',
										        height:wikiGridHeight,
										        containerScroll : true,
										    	viewConfig : {
//										    		stripeRows: true,
										            enableTextSelection: false
										    	},
										    	plugins: [cellEditing]
									    	});
									        
									        progrid.getEl().on('contextmenu', function(e, t) {
									            e.stopEvent();
									            rightMenu.showAt(e.getXY());
									        });
									        
//									        //右键触发事件
//									        function rightClickMenuFn(){
//									        	  alert(1);
//									        	  e.preventDefault();   
//									              //定位。显示 右键菜单
//									              rightMenu.show(e.getXY());
//									        };
////									        ‍
////									        // 给控件添加右键菜单触发事件(rowcontextmenu)
//									        progrid.addListener('rowcontextmenu', rightClickMenuFn);
									        myMask.hide();
//									    	progrid.render();
								    	}
							    	
							    	});
							
							
							    }
							},"-",databaseGroupCombo,"-",tableGroupCombo 
                         ]
                     }],
                     items: [
								{
								    region: 'north',
								    layout: 'fit',
								    border: false,
								    resizable:false,
								    collapsible: true,
				                    split: true,
				                    height: 100,
				                    minHeight: 100,
				                    header:false,
								    title: '',
								    items: [
											 sqlTextareaPanel
								            ]
								},{
								    region: 'center',
								    layout: 'fit',
								    border: true,
								    resizable:false,
								    collapsible: false,
				                    split: true,
				                    header:true,
				                    minHeight: 100,
				                    id:'r1',
								    title: 'Wiki生成区',
								    items: [
												{
												  title: '',
												  id: 'wikiGridId',
//												  width:500,
//												  height:400,
//												  layout: 'fit',
												  header:false,
												  html: '<div id=\"wikiGrid\"></div>'
												}
								           ]
								}
						    ]
                 }]
             });
         });

//
//function f_sqlTextarea_blur(obj){
//	if (obj.value == ''){
//		obj.value = '请输入SQL，仅支持Select语句';
//		obj.className = 'sqlTextarea_blur';
//	}
//}
//
//function f_sqlTextarea_focus(obj){
//	if (obj.value == '请输入SQL，仅支持Select语句'){
//		obj.value = '';
//		obj.className = 'sqlTextarea_focus';
//	}
//}